package org.carabiner.harness;

import java.awt.Component;
import java.awt.Window;
import java.lang.reflect.InvocationTargetException;

import javax.swing.SwingUtilities;

/**
 * Holds static factory methods used for creating and showing test harnesses
 * 
 * @author Ben Rady (benrady@gmail.com)
 * 
 */
public class HarnessFactory
{
  private HarnessFactory()
  {
  }

  /**
   * Creates a test harness for the given component
   *  
   * @param component
   * @return
   */
  public static Harness createHarness(Component component)
  {
    if (component instanceof Window)
    {
      return new WindowHarness((Window) component);
    }

    return new ComponentHarness(component);
  }

  /**
   * Shows the harness for a component, this method can be called from a main()
   * method within a test for a component.
   * 
   * @param component
   */
  public static void showHarness(final Component component)
  {
    Runnable runnable = new Runnable()
    {
      public void run()
      {
        Harness harness = HarnessFactory.createHarness(component);
        harness.showHarness();
      }
    };

    if (SwingUtilities.isEventDispatchThread())
    {
      runnable.run();
    }
    else
    {
      try
      {
        SwingUtilities.invokeAndWait(runnable);
      }
      catch (InterruptedException e)
      {
        throw new RuntimeException(e);
      }
      catch (InvocationTargetException e)
      {
        throw new RuntimeException(e);
      }
    }
  }
}
